import { useState } from "react";

const useWebsocket = (url: string) => {
  let socket = new WebSocket(url);
  const [message, setMessage] = useState("");
  // 建立连接
  socket.onmessage = (e) => {
    setMessage(e.data);
  };
  // 发送消息
  const sendMessage = (msg: string) => {
    socket.send(msg);
  };
  // 断线重连
  socket.onclose = () => {
    socket = new WebSocket(url);
  };

  return { message, sendMessage };
};

export default useWebsocket;
